import Vue from 'vue'
const _this = Vue.prototype
import { getBaseURL } from '@/config/server'
// import axios from 'axios'

// 移除仅H5支持的router，UniApp使用uni.navigateTo等路由API
// 注释未定义的环境判断函数（根据实际需求实现）
let isDDEnv = () => false
let isQYWXEnv = () => false

let apps = []
try {
  const appsString = uni.getStorageSync('appGroupList')
  if (appsString) {
    apps = JSON.parse(appsString)
  }
} catch (error) {
  console.error('解析应用列表失败', error)
}

// 根据appCode找到应用
function findApp(appCode) {
  let find = null
  for (const item of apps) {
    for (const child of item.appList) {
      if (child.appCode === appCode) {
        find = child
        break
      }
    }
    if (find) break
  }
  return find
}

function getServerIpPort() {
  try {
    // 统一使用UniApp存储API
    return uni.getStorageSync('serverIpPort') || ''
  } catch (error) {
    return ''
  }
}

const state = {
  appOrgInfo: uni.getStorageSync('appOrgInfo') ? JSON.parse(uni.getStorageSync('appOrgInfo')) : {},
  appUserInfo: {
    deptPositionInfo: [{}]
  },
  appList: [],
  quickApps: [],
  password: '',
  MessageTypeItem: {},
  loginForm: null,
  appGroupList: [],
  appContactList: [],
  orderRefresh: 1,
  firstShowUpdate: true,
  serverUrl: getServerIpPort(),
  badgeNum: 0, // 通知待办的角标数值
  orderTodoApp: findApp('order_todo_app') || {},
  todoProjectVisible: false,
  homeTodoProject: uni.getStorageSync('homeTodoProject') ? JSON.parse(uni.getStorageSync('homeTodoProject')) : {},
  workorderToken: '',
  sf_ygsk: findApp('sf_ygsk') || {},
  financeProjectVisible: false,
  homeFinanceProject: uni.getStorageSync('homeFinanceProject') ? JSON.parse(uni.getStorageSync('homeFinanceProject')) : {},
  homeFinanceProjectList: [],
  homeFinanceToken: '',
  ebaProject: {},
  commonConfig: [],
  noticeType: [],
  notSystemType: [],
  noticeToken: null,
  messageTypeList: [],
  messageAccessToken: '',
  firstAppAccessToken: '',
  aiMenuList: []
}

const getters = {}

const actions = {
  // 获取用户信息
  async getAppUserInfo({ commit }, { orgId }) {
    try {
      let res = await _this.$Posting(`${_this.$api.getAppUserInfo}?orgId=${orgId}`, `orgId=${orgId}`)
      if (res.code === '0') {
        commit('setAppUserInfo', res.data)
        // 非钉钉/企业微信环境且需要重置密码时跳转
        // if (!isDDEnv() && !isQYWXEnv() && res.data.initFlag === 1) {
        //   setTimeout(() => {
        //     // UniApp路由跳转
        //     uni.navigateTo({ url: '/pages/forgotPwd/forgotPwd' })
        //   }, 100)
        //   return Promise.resolve('重置密码')
        // }
      }
    } catch (error) {
      console.error('获取用户信息失败', error)
    }
  },

  // 获取应用列表
  async getAppGroupList({ commit }, { orgId }) {
    try {
      let res = await _this.$Geting(_this.$api.getAppGroupList, {
        orgId,
        terminalType: 2
      })
      if (res.code === '0') {
        commit('setAppGroupList', res.data && res.data.enterpriseAppGroup)
      }
    } catch (error) {
      console.error('获取应用列表失败', error)
    }
    return true
  },

  // 获取通讯录
  async getAppContactList({ commit }, { orgId }) {
    try {
      let res = await _this.$Geting(_this.$api.innerDeptGetDeptTreeNodes, {
        orgId
      })
      if (res.code === '0') {
        commit('setAppContactList', res.data)
      }
    } catch (error) {
      console.error('获取通讯录失败', error)
    }
  },

  // 获取首页收费相关数据
  async getHomeFinanceTokenAndProjectList({ commit, state }) {
    const appOrgInfo = uni.getStorageSync('appOrgInfo')
    if (!appOrgInfo) return

    try {
      const { memberId, orgId } = JSON.parse(appOrgInfo)
      let res = await _this.$Geting(_this.$api.getTokenByAppServiceId, {
        appServiceId: 'sf_ygsk',
        orgId,
        memberId
      })
      let token = res.data.accessToken

      // const { data } = await axios.get(`${getBaseURL()}${_this.$api.getFinanceProjectList}`, {
      //   headers: { 'X-Access-Source': 'roc', 'X-Access-Token': token }
      // })
      const {data} =await this.$Geting(_this.$api.getFinanceProjectList, {'X-Access-Source': 'roc', 'X-Access-Token': token})
      let list = data.data
      commit('setHomeFinanceTokenAndProjectList', { token, list })
    } catch (error) {
      console.error('获取收费项目数据失败', error)
    }
  },

  // 加载工单Token
  async loadWorkOrderToken({ commit, state }) {
    return new Promise(async (resolve, reject) => {
      if (!state.orderTodoApp.code) {
        resolve({ code: '-1', msg: '没有工单应用权限' })
        return
      }

      const appOrgInfo = uni.getStorageSync('appOrgInfo')
      if (!appOrgInfo) {
        resolve({ code: '-1', msg: '未获取到组织信息' })
        return
      }

      try {
        const { memberId, orgId } = JSON.parse(appOrgInfo)
        let res = await _this.$Geting(_this.$api.getTokenByAppServiceId, {
          appServiceId: 'order_center_app',
          orgId,
          memberId
        })
        let token = res.data.accessToken
        commit('setWorkorderToken', token)

        if (!state.homeTodoProject.projectId) {
          // const { data } = await axios.post(`${getBaseURL()}${_this.$api.getTodoProjectList}`, {
          //   pageNum: 1,
          //   pageSize: 20,
          //   query: ''
          // }, {
          //   headers: { 'X-Access-Source': 'roc', 'X-Access-Token': token }
          // })
          const {data} = await _this.$Posting(_this.$api.getTodoProjectList, {pageNum: 1,pageSize: 20, query: ''}, {headers: { 'X-Access-Source': 'roc', 'X-Access-Token': token }})
          let { list } = data.data || {}
          list = list.map(x => x.projectWebResultDto)
          if (list.length) {
            commit('setHomeTodoProject', list[0])
          }
        }
        resolve(token)
      } catch (error) {
        console.error('加载工单Token失败', error)
        reject(error)
      }
    })
  },

  // 获取通用配置信息
  async getConmmonConfigInfo({ commit }) {
    try {
      let res = await _this.$Geting(_this.$api.commonConfigList)
      if (res && res.code === '0') {
        commit('setConmmonConfigInfo', res.data)
      }
    } catch (error) {
      console.error('获取通用配置失败', error)
    }
  },

  // 获取公告类型数据
  async getOptionSetData({ state, commit }) {
    try {
      let res = await _this.$Geting(_this.$api.getTypeOptions, {
        tenantId: state.appOrgInfo.orgId,
        typeCode: '98003'
      })
      if (res.isSuccess) {
        const resData = res.data
        commit('setNoticeType', resData)
        state.notSystemType = resData.filter(item => +item.factorySetting === 0)
      }
      return res
    } catch (error) {
      console.error('获取公告类型失败', error)
      return { isSuccess: false }
    }
  },

  async loadFirtAppAccessToken({ state, commit }) {
    try {
      let firstApp = ''
      const appsString = uni.getStorageSync('appGroupList')
      let tempApps = []
      if (appsString) {
        tempApps = JSON.parse(appsString)
      }

      // 查找第一个应用
      for (const item of tempApps) {
        for (const child of item.appList) {
          if (!firstApp) {
            firstApp = child
            break
          }
        }
        if (firstApp) break
      }

      if (!firstApp) return

      const appOrgInfo = uni.getStorageSync('appOrgInfo')
      if (!appOrgInfo) return

      const { memberId, orgId } = JSON.parse(appOrgInfo)
      let res = await _this.$Geting(_this.$api.getTokenByAppIdMemberIdOrgId, {
        appId: firstApp.relationAppId,
        orgId,
        memberId
      })
      let token = res.data.accessToken
      // 使用UniApp存储API
      uni.setStorageSync('messagewebToken', token)
      commit('setFirstAppAccessToken', token)
      return token
    } catch (error) {
      console.error('获取首个应用Token失败', error)
    }
  },

  // 获取消息类型数据列表
  async getMessageTypeList({ state, commit }) {
    try {
      if (!state.messageAccessToken) {
        await getMessageAccessToken()
      }

      async function getMessageAccessToken() {
        return new Promise(async (resolve) => {
          let firstApp = ''
          const appsString = uni.getStorageSync('appGroupList')
          let tempApps = []
          if (appsString) {
            tempApps = JSON.parse(appsString)
          }

          for (const item of tempApps) {
            for (const child of item.appList) {
              if (!firstApp) {
                firstApp = child
                break
              }
            }
            if (firstApp) break
          }

          if (!firstApp) {
            resolve(null)
            return
          }

          const appOrgInfo = uni.getStorageSync('appOrgInfo')
          if (!appOrgInfo) {
            resolve(null)
            return
          }

          const { memberId, orgId } = JSON.parse(appOrgInfo)
          let res = await _this.$Geting(_this.$api.getTokenByAppIdMemberIdOrgId, {
            appId: firstApp.relationAppId,
            orgId,
            memberId
          })
          let token = res.data.accessToken
          state.messageAccessToken = token
          console.log(token, 'token')
          commit('setMessageAccessToken', token)
          resolve(token)
        })
      }

      // 请求消息类型列表
      // let { data } = await axios.get(`${getBaseURL()}${_this.$api.messageclassificationlistinterface}?userId=${state.appOrgInfo.memberId}&terminal=1`, {
        // headers: { 'X-Access-Source': 'roc', 'X-Access-Token': state.messageAccessToken }
      // })
      let hasdata = await _this.$Geting(_this.$api.messageclassificationlistinterface, {userId:state.appOrgInfo.memberId, terminal: 1}, { 'X-Access-Source': 'roc', 'X-Access-Token': state.messageAccessToken })
      console.log(hasdata, 'hasdata')

      let list = []
      if (hasdata.code === '0') {
        list = hasdata.data
      } else if (hasdata.code === '-200') {
        // Token过期重新获取
        await getMessageAccessToken()
        // let resp = await this.$Geting(`_this.$api.messageclassificationlistinterface}?userId=${state.appOrgInfo.memberId}&terminal=1`, {
        //   headers: { 'X-Access-Source': 'roc', 'X-Access-Token': state.messageAccessToken }
        // })
        let resp =await this.$Geting(this.$api.messageclassificationlistinterface, {userId: state.appOrgInfo.memberId,terminal:1}, {
          'X-Access-Source': 'roc', 'X-Access-Token': state.messageAccessToken
        })
        if (resp.data.code === '0') {
          list = resp.data.data
        }
      }

      // list = list.filter(x => x.count > 0 || (x.readCount || 0) > 0)
      console.log(list, '消息列表')
      commit('setMessageTypeList', list)
    } catch (error) {
      console.error('获取消息类型列表失败', error)
    }
  },

  // 获取AI菜单列表
  async getAiMenuList({ commit }) {
    try {
      const appOrgInfo = uni.getStorageSync('appOrgInfo')
      if (!appOrgInfo) return

      const { memberId, orgId } = JSON.parse(appOrgInfo)
      let accessToken = ''

      let resToken = await _this.$Geting(_this.$api.getTokenByAppServiceId, {
        appServiceId: 'system_log',
        orgId,
        memberId
      })
      if (resToken.isSuccess) {
        accessToken = resToken.data.accessToken
      }

      const res2 = await _this.$Posting(_this.$api.agentConfigName, {}, false, {
        headers: {
          'X-Access-Source': 'roc',
          'X-Access-Token': accessToken || ''
        }
      })
      if (res2.isSuccess) {
        commit('setAiMenuList', res2.data)
      }
    } catch (error) {
      console.error('获取AI菜单列表失败', error)
    }
  }
}

const mutations = {
  setPassword(state, pwd) {
    state.password = pwd
  },
  setLoginForm(state, data) {
    state.loginForm = data
  },
  setApps(state, apps) {
    state.appList = apps
  },
  setQuickApps(state, apps) {
    state.quickApps = apps
  },
  setServerUrl(state, url) {
    state.serverUrl = url
  },
  setAppOrgInfo(state, playLoad) {
    state.appOrgInfo = { ...playLoad }
    uni.setStorageSync('appOrgInfo', JSON.stringify(playLoad))
  },
  setAppUserInfo(state, playLoad) {
    state.appUserInfo = { ...playLoad }
    const userInfo = JSON.stringify(playLoad)
    uni.setStorageSync('appUserInfo', userInfo)
  },
  setAppGroupList(state, playLoad) {
    state.appGroupList = [...playLoad]
    let code = ''
    const arr = playLoad.map(item => {
      item.appList.forEach((list) => {
        if (!code) {
          code = list.code
        }
        if (list.appCode === 'order_todo_app') {
          state.orderTodoApp = list
        } else if (list.appCode === 'sf_ygsk') {
          state.sf_ygsk = list
        }
      })
      return item
    })
    playLoad = arr.filter(item => item.appList.length)
    uni.setStorageSync('appGroupList', JSON.stringify(playLoad))
  },
  setAppContactList(state, playLoad) {
    state.appContactList = [...playLoad]
    uni.setStorageSync('appContactList', JSON.stringify(playLoad))
  },
  setMessageTypeItem(state, playLoad) {
    state.MessageTypeItem = Object.assign({},playLoad)
  },
  setBadgeNum(state, payLoad) {
    state.badgeNum = payLoad
    if (uni.setTabBarBadge) {
      uni.setTabBarBadge({
        index: 1, 
        text: payLoad > 99 ? '99+' : payLoad.toString()
      })
    }
  },
  setOrderRefresh(state) {
    state.orderRefresh++
  },
  setFirstShowUpdate(state, payLoad) {
    state.firstShowUpdate = payLoad
  },
  setHomeTodoProject(state, payload) {
    state.homeTodoProject = payload
    uni.setStorageSync('homeTodoProject', JSON.stringify(payload))
  },
  setTodoProjectVisible(state, payload) {
    state.todoProjectVisible = payload
  },
  setHomeFinanceProject(state, payload) {
    state.homeFinanceProject = payload
    uni.setStorageSync('homeFinanceProject', JSON.stringify(payload))
  },
  setFinanceProjectVisible(state, payload) {
    state.financeProjectVisible = payload
  },
  setHomeFinanceProjectList(state, payload) {
    state.homeFinanceProjectList = payload
  },
  setHomeFinanceTokenAndProjectList(state, payload) {
    state.homeFinanceToken = payload.token
    state.homeFinanceProjectList = payload.list
    if (payload.list.length) {
      let firstProject = payload.list[0]
      state.homeFinanceProject = firstProject
      state.ebaProject = firstProject
      uni.setStorageSync('homeFinanceProject', JSON.stringify(firstProject))
    }
  },
  setWorkorderToken(state, data) {
    state.workorderToken = data
  },
  setEbaProject(state, data) {
    state.ebaProject = data
  },
  setConmmonConfigInfo(state, data) {
    state.commonConfig = data
  },
  setNoticeType(state, payload) {
    state.noticeType = payload
  },
  setNoticeToken(state, data) {
    state.noticeToken = data || null
  },
  setOrderTodoApp(state, app) {
    state.orderTodoApp = app
  },
  clearLastLocalApp(state) {
    state.orderTodoApp = {}
    state.sf_ygsk = {}
  },
  setMessageAccessToken(state, token) {
    state.messageAccessToken = token
  },
  setMessageTypeList(state, list) {
    state.messageTypeList = list
  },
  setFirstAppAccessToken(state, token) {
    state.firstAppAccessToken = token
  },
  setAiMenuList(state, menuList) {
    state.aiMenuList = menuList
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}